package com.ys.arch.splitamount.algorithm.core;

import com.ys.arch.splitamount.algorithm.execption.SplitAmountAlgorithmException;
import com.ys.arch.splitamount.algorithm.support.Pair;
import com.ys.arch.splitamount.algorithm.utils.AmountUtil;

import java.math.BigDecimal;

/**
 * <p>@description:计算占比算法</>
 *
 * @author shuang.yang
 * @version 1.0
 * @create 2021/12/25/17:57
 */
public class SplitAlgorithmRateCalculateHelper {
    public final static int scale = 10;

    /**
     * 计算占比
     *
     * @param totalAmount   总的应付金额
     * @param currentAmount 当前的金额
     * @param isLastItem    是否最后一个
     * @param addRate       累计占比
     * @return
     */
    public static Pair<BigDecimal/*currentRate*/, BigDecimal/*accRate*/> calculateRate(BigDecimal totalAmount,
                                                                                       BigDecimal currentAmount,
                                                                                       boolean isLastItem,
                                                                                       BigDecimal addRate) {
        BigDecimal rate;
        if (!AmountUtil.predicateBigDecimalNotNullAndNotZero.test(currentAmount)) {
            rate = new BigDecimal("0");
        } else {
            //最后一个
            if (isLastItem) {
                rate = AmountUtil.sub(BigDecimal.ONE, addRate, scale);
                if (rate.doubleValue() < 0) {
                    throw new SplitAmountAlgorithmException("金额分摊小于0出现错误");
                }
            } else {
                //其他行
                rate = AmountUtil.divide(currentAmount, totalAmount, scale);
                BigDecimal tempRate = AmountUtil.add(addRate, rate, scale);
                if (tempRate.doubleValue() > 1) {
                    rate = AmountUtil.sub(rate, AmountUtil.sub(tempRate, BigDecimal.ONE, scale));
                }
                addRate = AmountUtil.add(addRate, rate, scale);
            }
        }
        return Pair.of(rate, addRate);
    }
}
